const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { body, validationResult } = require('express-validator');
const { authenticateToken, generateString, encryptPhone, decryptPhone, extractNumber, logUserOperation } = require('../untils/untils');
const dayjs = require('dayjs')
const { cryptoHelper } = require('../config/global');

// 获取岗位列表
// { "position_name": "前端", "dept_id": "" }
router.get('/', authenticateToken, async (req, res) => {
    try {
        const { position_name, dept_id } = req.query;
        let sql = `SELECT position.*, department.dept_name FROM position INNER JOIN department ON position.dept_id = department.dept_id`;
        if (position_name) {
            sql += ` WHERE position.position_name LIKE '%${position_name}%'`;
        }
        if (dept_id) {
            sql += ` WHERE position.dept_id = '${dept_id}'`;
        }
        let [result] = await db.execute(sql);
        result.forEach(item => {
            item.create_time = dayjs(item.create_time).format('YYYY-MM-DD HH:mm:ss');
        });
        await logUserOperation(req, '查询', '获取岗位列表', '获取岗位列表成功', '成功');
        res.json({
            success: true,
            message: '获取岗位列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取岗位列表失败:', error);
        await logUserOperation(req, '查询', '获取岗位列表', '获取岗位列表失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '获取岗位列表失败',
            error: error.message
        });
    }
});

// 添加岗位
router.put('/add', authenticateToken, async (req, res) => {
    try {
        const { position_name, dept_id } = req.body;
        const create_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
        
        // 获取数据库中最大的position_id P00001
        const [maxPositionId] = await db.execute(
            'SELECT MAX(position_id) AS max_position_id FROM position'
        );
        let nextId = 1;
        if (maxPositionId[0].max_position_id) {
            // 提取数字部分并加1
            const currentNumber = extractNumber(maxPositionId[0].max_position_id);
            nextId = currentNumber + 1;
        }
        const position_id = generateString('P', nextId, 3);
        let sql = 'INSERT INTO `position` (position_id, position_name, dept_id, create_time) VALUES (?, ?, ?, ?)';
        let params = [position_id, position_name, dept_id, create_time];
        const [result] = await db.execute(sql, params);
        await logUserOperation(req, '添加', '添加岗位', '添加岗位成功', '成功');
        res.json({
            success: true,
            message: '添加岗位成功',
            data: result
        });
    } catch (error) {
        console.error('添加岗位失败:', error);
        await logUserOperation(req, '添加', '添加岗位', '添加岗位失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '添加岗位失败',
            error: error.message
        });
    }
});

// 修改岗位
router.post('/update', authenticateToken, async (req, res) => {
    try {
        const { position_id, position_name, dept_id } = req.body;
        let sql = 'UPDATE `position` SET position_name = ?, dept_id = ? WHERE position_id = ?';
        let params = [position_name, dept_id, position_id];
        const [result] = await db.execute(sql, params);
        await logUserOperation(req, '更新', '更新岗位', '更新岗位成功', '成功');
        res.json({
            success: true,
            message: '修改岗位成功',
            data: result
        });
    } catch (error) {
        console.error('修改岗位失败:', error);
        await logUserOperation(req, '更新', '更新岗位', '更新岗位失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '修改岗位失败',
            error: error.message
        });
    }
});

// 删除岗位
router.delete('/delete', authenticateToken, async (req, res) => {
    try {
        const { position_id } = req.query;
        let sql = 'DELETE FROM `position` WHERE position_id = ?';
        let params = [position_id];
        const [result] = await db.execute(sql, params);
        await logUserOperation(req, '删除', '删除岗位', '删除岗位成功', '成功');
        res.json({
            success: true,
            message: '删除岗位成功',
            data: result
        });
    } catch (error) {
        console.error('删除岗位失败:', error);
        await logUserOperation(req, '删除', '删除岗位', '删除岗位失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '删除岗位失败',
            error: error.message
        });
    }
});

// 获取部门列表
router.get('/getDepartment', authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT dept_id as 'key', dept_name as 'name' FROM department`;
        let [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取部门列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取部门列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取部门列表失败',
            error: error.message
        });
    }
});

// 获取查询项部门
router.get('/getDepartmentForQuery', authenticateToken, async (req, res) => {
    try {
        // 去重获取查询项部门
        let sql = `SELECT DISTINCT department.dept_id as 'key', department.dept_name as 'name' FROM department INNER JOIN position ON department.dept_id = position.dept_id`;
        let [result] = await db.execute(sql);   
        res.json({
            success: true,
            message: '获取查询项部门成功',
            data: result
        });
    } catch (error) {
        console.error('获取查询项部门失败:', error);
        res.status(500).json({
            success: false,
            message: '获取查询项部门失败',
            error: error.message
        });
    }
});

module.exports = router;
